#
# Copyright (c) 2023 supercell
#
# SPDX-License-Identifier: BSD-3-Clause
#
require "http/client"
require "json"

# update_github_emojis.dart now generates the emoji list using the GitHub API
# to retrieve the emoji list.  It uses this emoji source as a source to keep
# binary compatibility with the Unicode sequences for each emoji found here.
EMOJIS_JSON_RAW_URL = "https://raw.githubusercontent.com/muan/emojilib/v2.4.0/emojis.json"
EMOJIS_FILE_PATH    = "src/luce/legacy_emojis.cr"

response = HTTP::Client.get(URI.parse EMOJIS_JSON_RAW_URL)
json = Hash(String, Hash(String, JSON::Any?)).from_json response.body
emoji_content = String::Builder.new
emoji_content << <<-EOS
# GENERATED FILE. DO NOT EDIT.
#
# This file was generated from emojilib's data file:
# #{EMOJIS_JSON_RAW_URL}
# at #{Time.utc} by the script, tools/update_emojis.cr.
\n
EOS

emoji_content.puts "module Luce"
emoji_content.puts "  class LegacyEmojis"
emoji_content.puts
emoji_content.puts "    # Returns the emoji for *name*"
emoji_content.puts "    def self.[](name : String) : String"
emoji_content.puts "      @@hash[name]"
emoji_content.puts "    end"
emoji_content.puts
emoji_content.puts "    # Returns the emoji for *name*, or `nil` if no emoji exists."
emoji_content.puts "    def self.[]?(name : String) : String?"
emoji_content.puts "      @@hash.fetch(name, nil)"
emoji_content.puts "    end"
emoji_content.puts
emoji_content.puts "    def self.each(& : Tuple(String, String) -> ) : Nil"
emoji_content.puts "      @@hash.each { |key| yield key }"
emoji_content.puts "    end"
emoji_content.puts
emoji_content.puts "    def self.includes?(key : String) : Bool"
emoji_content.puts "      @@hash.includes?(key)"
emoji_content.puts "    end"
emoji_content.puts
emoji_content.puts "    @@hash : Hash(String, String) = {"

emoji_count = 0
ignored = [] of String

# Dump in sorted order now to facilitate comparison with new GitHub emoji
sorted_keys = json.keys.sort!
sorted_keys.each do |name|
  info = json[name]
  if info.has_key?("char")
    emoji_content.puts "      \"#{name}\" => \"#{info["char"]}\","
    emoji_count += 1
  else
    ignored << name
  end
end

emoji_content.puts "    }" # end of @@hash definition
emoji_content.puts "  end" # class Emojis
emoji_content.puts "end"   # module Luce

File.write(EMOJIS_FILE_PATH, emoji_content.to_s)

puts "WARNING: This updates only the LEGACY emoji - to update the active\n" +
     "emoji recognized by luce, execute `update_github_emojis.cr`.\n"
puts "Wrote data to #{EMOJIS_FILE_PATH} for #{emoji_count} emoji, " +
     "ignoring #{ignored.size}: #{ignored.join(", ")}."

Process.run("crystal", ["tool", "format", EMOJIS_FILE_PATH])
